<template>
  <div class="media_message_container">
    <van-image @click="clickMediaItem" class="need_preload_message w-[300px] h-[200px]" :class="{ 'h-8 w-8': isError }"
      fit="contain" radius="6" :src="imageUrl" @error="isError = true">
      <template v-slot:loading>
        <van-loading type="spinner" size="20" />
      </template>
      <template v-slot:error>{{ $t('messageTip.failLoad') }}</template>
    </van-image>
    <van-image-preview @click="show = false" v-model:show="show" :images="[imageUrl]">
    </van-image-preview>
    <img v-if="isVideo" @click="clickMediaItem" class="play_icon" :src="play_icon" alt="" />
    <text v-if="isVideo" class="video_duration">{{ duration }}</text>
    <van-overlay :show="isVideoShow" @click="isVideoShow = false">
      <div class="wrapper" @click.stop>
        <div class="close_icon" @click="isVideoShow = false">关闭</div>
        <PreviewVideo v-if="isVideoShow" :url="props.message.videoElem?.videoUrl"
          :poster="props.message.videoElem?.snapshotUrl" />
      </div>
    </van-overlay>
  </div>
</template>

<script setup lang="ts">
import play_icon from '@/assets/images/chating_message_video_play.png'
import { secFormat } from '@/utils/common'
import { MessageType } from '@openim/wasm-client-sdk'
import { showImagePreview } from 'vant'
import { ExedMessageItem } from './data'
import PreviewVideo from '@pages/conversation/previewVideo/index.vue'
import { handleError } from 'vue'

type MediaMessageRendererProps = {
  message: ExedMessageItem
  disabled: boolean
}

const props = defineProps<MediaMessageRendererProps>()

const isError = ref(false)

const isVideo = props.message.contentType === MessageType.VideoMessage
const imageUrl = isVideo
  ? props.message.videoElem?.snapshotUrl
  : props.message.pictureElem?.snapshotPicture.url
const duration = isVideo ? secFormat(props.message.videoElem?.duration) : 0

const isVideoShow = ref(false)
const show = ref(false)

const clickMediaItem = () => {
  if (props.disabled) {
    return
  }
  if (isVideo) {
    isVideoShow.value = true
  } else {
    show.value = true
    // showImagePreview({
    //   images: [props.message.pictureElem?.sourcePicture.url!],
    //   startPosition: 0,
    //   loop: false,
    //   closeable: true
    // })
  }
}
</script>

<style lang="scss" scoped>
.media_message_container {
  position: relative;
  overflow: hidden;

  .play_icon {
    width: 36px;
    height: 36px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .video_duration {
    position: absolute;
    bottom: 6px;
    right: 12px;
    color: #fff;
  }
}

:deep(.van-overlay) {
  z-index: 9999;
}

.wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .close_icon {
    position: fixed;
    right: 2rem;
    top: 2rem;
    color: #fff;
    cursor: pointer;
  }
}
</style>
